<template>
    <div>
        <app-head></app-head>
        <app-body>
            <div class="release-idle-container">
                <div class="release-idle-container-title">物品编辑</div>
                <div class="release-idle-container-form">
                    <el-input
                        placeholder="请输入二手物品名称"
                        v-model="ProductEditDto.productName"
                        maxlength="30"
                        show-word-limit
                    ></el-input>

                    <el-input
                        class="release-idle-detiles-text"
                        type="textarea"
                        autosize
                        placeholder="请输入物品的详细介绍..."
                        v-model="ProductEditDto.description"
                        maxlength="1000"
                        show-word-limit
                    ></el-input>

                    <div class="release-tip">物品类别</div>
                    <el-select v-model="ProductEditDto.categoryId" placeholder="请选择类别">
                        <el-option
                            v-for="item in options2"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        ></el-option>
                    </el-select>

                    <div style="margin-top: 10px;">
                        <div class="release-tip">价格</div>
                        <el-input-number
                            v-model="ProductEditDto.price"
                            :precision="2"
                            :step="5"
                            :min="0.01"
                            :max="10000000"
                        ></el-input-number>
                    </div>

                    <div class="release-idle-container-picture">
                        <div class="release-idle-container-picture-title">上传二手物品照片</div>
                        <el-upload
                            action="http://10.192.149.34:30090/products/upload/image"
                            :headers="authHeaders"
                            :on-preview="fileHandlePreview"
                            :on-remove="fileHandleRemove"
                            :on-success="fileHandleSuccess"
                            :file-list="fileList"
                            :show-file-list="true"
                            :limit="10"
                            :on-exceed="handleExceed"
                            accept="image/*"
                            drag
                            multiple
                        >
                            <i class="el-icon-upload"></i>
                            <div class="el-upload__text">将图片拖到此处，或<em>点击上传</em></div>
                        </el-upload>

                        <div class="picture-list">
                            <el-image
                                style="width: 600px; height: 400px; margin-bottom: 2px;"
                                fit="contain"
                                v-for="(img, index) in ProductEditDto.images"
                                :key="index"
                                :src="img"
                                :preview-src-list="ProductEditDto.images"
                                @click="previewImage(img)"
                            ></el-image>
                        </div>

                        <el-dialog :visible.sync="previewVisible">
                            <img width="100%" :src="previewImageUrl" alt="商品图片预览" />
                        </el-dialog>
                    </div>

                    <div style="display: flex; justify-content: center; margin-top: 30px; margin-bottom: 30px;">
                        <el-button type="primary" @click="saveEdit">保存修改</el-button>
                        <el-button @click="cancelEdit">取消</el-button>
                    </div>
                </div>
            </div>
            <app-foot></app-foot>
        </app-body>
    </div>
</template>

<script>
import AppHead from '../common/AppHeader.vue';
import AppBody from '../common/AppPageBody.vue';
import AppFoot from '../common/AppFoot.vue';

export default {
    name: "editProduct",
    components: {
        AppHead,
        AppBody,
        AppFoot
    },
    data() {
        return {
            previewVisible: false,
            previewImageUrl: '',
            options2: [], // 分类列表
            fileList: [], // 上传文件列表
            ProductEditDto: {
                productName: '',
                description: '',
                images: [], // 图片URL数组
                price: 0,
                categoryId: ''
            }
        };
    },
    computed: {
        authHeaders() {
            return {
                Authorization: `Bearer ${window.localStorage.getItem('token')}`
            };
        }
    },
    mounted() {
        this.getCategories();
        this.loadProduct();
    },
    methods: {
        // 加载商品详情
        loadProduct() {
            const productId = this.$route.query.productId;
            if (!productId) {
                this.$message.error('缺少商品ID');
                return;
            }

            this.$api.getProductDetail(productId).then((res) => {
                if (res.code === 200) {
                    const data = res.data;

                    // 强制转换为数组形式（处理返回是逗号分隔字符串的情况）
                    if (typeof data.images === 'string') {
                        data.images = data.images.split(',').filter(Boolean);  // 过滤空字符串
                    } else if (!Array.isArray(data.images)) {
                        data.images = [];
                    }

                    // 回填表单字段
                    this.ProductEditDto.productName = data.productName || '';
                    this.ProductEditDto.description = data.productDescription || '';
                    this.ProductEditDto.price = data.productPrice || 0;
                    this.ProductEditDto.categoryId = data.productCategory.id || '';
                    this.ProductEditDto.images = data.images;

                    // 同步 fileList 供上传组件展示
                    this.fileList = data.images.map((url, index) => ({
                        name: `图片-${index + 1}`,
                        url: url,
                        response: { data: url }
                    }));
                } else {
                    this.$message.error('加载商品详情失败');
                }
            }).catch(() => {
                this.$message.error('请求商品详情接口失败');
            });
        },
        // 获取分类列表
        getCategories() {
            this.$api.getAllClassification().then(res => {
                if (res.code === 200) {
                    this.options2 = res.data.map(item => ({
                        value: item.id,
                        label: item.name
                    }));
                } else {
                    this.$message.error('获取分类失败：' + res.msg);
                }
            }).catch(() => {
                this.$message.error('请求分类接口出错');
            });
        },

        // 图片上传成功处理
        fileHandleSuccess(response, file, fileList) {
            if (response && response.data) {
                const imageUrl = response.data;
                if (!this.ProductEditDto.images.includes(imageUrl)) {
                    this.ProductEditDto.images.push(imageUrl);
                }
                this.$message.success('图片上传成功');
            } else {
                this.$message.error('图片上传失败');
            }
        },


        //删除图片时触发的方法，更新本地图片列表。
        fileHandleRemove(file, fileList) {
            let urlToRemove = "";
            if (file.response && file.response.data) {
                urlToRemove = file.response.data;
            } else if (file.url) {
                urlToRemove = file.url;
            }
            if (urlToRemove) {
                this.ProductEditDto.images = this.ProductEditDto.images.filter(img => img !== urlToRemove);
            }
        },

        //点击文件列表中的图片时调用的方法，用于预览
        fileHandlePreview(file) {
            if (file.response && file.response.data) {
                this.previewImageUrl = file.response.data;
            } else if (file.url) {
                this.previewImageUrl = file.url;
            } else if (file.raw) {
                const reader = new FileReader();
                reader.readAsDataURL(file.raw);
                reader.onload = e => {
                    this.previewImageUrl = e.target.result;
                    this.previewVisible = true;
                };
                return;
            }
            this.previewVisible = true;
        },

        // 图片超出限制处理
        handleExceed(files, fileList) {
            this.$message.warning(`最多上传10张图片，当前已选择 ${files.length + fileList.length} 张`);
        },

        // 点击图片预览
        previewImage(url) {
            this.previewImageUrl = url;
            this.previewVisible = true;
        },

        // 保存修改
        saveEdit() {
            if (!this.validateForm()) return;
            const productId = this.$route.query.productId;
            this.$api.editItem(productId, this.ProductEditDto).then(res => {
                if (res.code === 200) {
                    this.$message.success('修改成功');
                    this.$router.push(`/details?productId=${productId}`);
                } else {
                    this.$message.error('修改失败：' + res.msg);
                }
            }).catch(() => {
                this.$message.error('请求失败，请稍后重试');
            });
        },

        // 取消编辑
        cancelEdit() {
            this.$router.back();
        },

        // 表单验证
        validateForm() {
            if (!this.ProductEditDto.productName) {
                this.$message.error('请输入商品名称');
                return false;
            }

            if (!this.ProductEditDto.description) {
                this.$message.error('请输入商品描述');
                return false;
            }

            if (!this.ProductEditDto.categoryId) {
                this.$message.error('请选择商品类别');
                return false;
            }

            if (!this.ProductEditDto.price || this.ProductEditDto.price <= 0) {
                this.$message.error('请输入有效的价格');
                return false;
            }

            if (this.ProductEditDto.images.length === 0) {
                this.$message.error('请上传至少一张商品图片');
                return false;
            }

            return true;
        }
    }
}
</script>

<style scoped>
/* 复用发布页布局样式，保持视觉一致 */
.release-idle-container {
    width: 80%;
    margin: 40px auto;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    overflow: hidden;
}

.release-idle-container-title {
    font-size: 18px;
    font-weight: bold;
    color: #333;
    padding: 20px;
    border-bottom: 1px solid #eee;
}

.release-idle-container-form {
    padding: 30px;
}

/* 输入框样式对齐 */
.el-input,
.el-textarea,
.el-select,
.el-input-number {
    width: 100%;
    margin-bottom: 20px;
}

.release-idle-detiles-text {
    width: 100%;
}

/* 提示文本样式 */
.release-tip {
    font-size: 14px;
    color: #666;
    margin: 10px 0 5px;
}

/* 图片上传区域样式 */
.release-idle-container-picture {
    margin-top: 20px;
}

.release-idle-container-picture-title {
    font-size: 14px;
    font-weight: 500;
    color: #333;
    margin-bottom: 10px;
}

/* 图片预览列表 */
.picture-list {
    margin-top: 10px;
}

/* 按钮区域对齐 */
.el-button-group {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

/* 适配响应式布局 */
@media (max-width: 768px) {
    .release-idle-container {
        width: 95%;
    }

    .el-image {
        width: 100% !important;
        height: auto !important;
    }
}
</style>